import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { CustomerShopService } from './customer-shop.service';
import { NzModalService } from 'ng-zorro-antd/modal';
import { format, formatDistance, formatRelative, subDays } from 'date-fns'
import { defalutImg } from '../../../comm';
import { CommonService } from '../../../services-common/common.service';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
    selector: 'app-customer-shop',
    templateUrl: './customer-shop.component.html',
    styleUrls: ['./customer-shop.component.scss']
})
export class CustomerShopComponent implements OnInit {
    id: any = null;
    /**
     * 全局 loading
     */
    messageId: any = null;
    /**
     * 详情数据
     */
    detailsData: any = null;
    auditVisible = false;
    /**
     * 审核
     */
    auditParams: any = {
        id: 0,
        status: "3", // 0 无效( 已删除 ) 1待完善 2待审核 3审核通过 4 审核不通过  10 暂不认证
        uscc: '', // 社会信用代码
        businessRegisterTime: '', // 执行注册日期
        juridicalBirthday: '', // 法人生日
        juridicalSex: 0, // 性别：0未知 1男 2女
        // accountType: '', // 账号属性 0：正常 1：测试
        userId:"", // 用户ID
        auditReason: "" // 备注
    };
    /**
     * 加载失败显示图像占位符
     */
    fallback = defalutImg;
    // 提交入口list
    entranceList: any = [];

    resetStatusLoading = false;

    // 账号属性
    accountAttribute: string | number = '';
    subAccountLoaidng: boolean = false;

    /**
     * 商家地图属性修改
     * ----------------------------------------------------------------
     */
    isMapVisible = false;
    submitMapLoading = false;
    validateMapForm!: FormGroup;

    constructor(
        private router: Router,
        private activatedRoute: ActivatedRoute,
        private message: NzMessageService,
        private CustomerShopService: CustomerShopService,
        private commonService: CommonService,
        private fb: FormBuilder,
        private modal: NzModalService
    ) { }

    ngOnInit() {
        this.validateMapForm = this.fb.group({
            mapName: ['', [Validators.required]], // 商家名称
            accountType: ['', [Validators.required]] // 账号属性 0 正常 1 测试 2 内部同事推荐
        });
        this.queryDictData();
        this.activatedRoute.params.subscribe(params => {
            this.id = params.id;
        });
        this.details();
    }

    /**
     * 打开模态框
     */
    showAuditModal() {
        this.auditParams.uscc = this.detailsData.uscc || '';
        this.auditParams.businessRegisterTime = this.detailsData.businessRegisterTime || ''; // 执行注册日期
        this.auditParams.juridicalBirthday = this.detailsData.juridicalBirthday || ''; // 法人生日
        this.auditParams.juridicalSex = this.detailsData.juridicalSex || 0; // 性别：0未知 1男 2女
        // this.auditParams.accountType = !this.commonService.isEmpty(this.detailsData.accountType) ? Number(this.detailsData.accountType) : ''; // 账号属性 0：正常 1：测试
        this.auditVisible = true;
    }
    /**
     * 关闭模态框
     */
    handleCancel() {
        this.auditVisible = false;
    }
    /**
     * 审核确定按钮
     */
    async closeFun() {
        const { status, auditReason } = this.auditParams
        if (this.messageId != null) {
            return;
        }
        if (status == 4 && !auditReason) {
            this.message.warning('请输入备注')
            return
        }
        if (status == 3 && this.commonService.isEmpty(this.auditParams.juridicalSex)) {
            this.message.warning('请选择性别')
            return
        }
        // if (status == 3 && this.commonService.isEmpty(this.auditParams.accountType)) {
        //     this.message.warning('请选择账号属性')
        //     return
        // }

        this.auditParams.id = this.detailsData.id;
        this.auditParams.userId = this.detailsData.userId;
        
        if (status === '3' && this.auditParams.uscc) {
            const res: any = await this.CustomerShopService.verifUsccData({id: this.detailsData.id, uscc: this.auditParams.uscc});
            if (res.data && res.data !== '0') {
                this.modal.confirm({
                    nzTitle: '提示',
                    nzContent: `信用代码已存在，门店ID是：<b>${res.data}</b>，是否继续通过？`,
                    nzOkText: '确定',
                    nzOkType: 'primary',
                    nzOkDanger: true,
                    nzOnOk: () => {
                        this.examineInterface();
                    },
                    nzCancelText: '取消',
                });
                return
            }
        }
        this.examineInterface();
    }
    // 审核 Interface
    examineInterface() {
        this.createBasicMessage();
        this.CustomerShopService.audit(this.auditParams).subscribe((res: any) => {
            this.removeBasicMessage();
            if (res.code != 0) {
                this.createMessage("error", res.message);
                return;
            }
            this.createMessage("success", "门店信息审核成功");
            this.handleCancel();
            this.details();
        }, err => {
            this.removeBasicMessage();
            this.createMessage("error", err.message);
        })
    }
    /**
     * 获取详情
     */
    details() {
        this.CustomerShopService.details({ id: this.id, type: 1 }).subscribe((res: any) => {
            if (res.code != 0) {
                this.createMessage("error", res.message);
                return;
            }
            const { data } = res
            const { list } = data || {}
            if (list?.length > 0) {
                this.detailsData = list[0];
                this.detailsData.companyImgs = this.detailsData?.companyImgs ? this.detailsData?.companyImgs.split(',') : [];
                let serArr = this.detailsData.serviceTypes ? this.detailsData.serviceTypes.split(',') : [];
                let strArr: any = [];
                for (let index = 0; index < serArr.length; index++) {
                    const element = serArr[index];
                    if (element == 1) {
                        strArr.push("普通维修");
                    } else if (element == 2) {
                        strArr.push("高级维修");
                    } else if (element == 3) {
                        strArr.push("手机&配件买卖");
                    }
                }
                this.detailsData.service = strArr;

                this.accountAttribute = this.detailsData.accountType;
            }

        }, err => {
            this.createMessage("error", err.message);
        })
    }
    status_to_text(status: any) {
        let text = "";
        switch (status) {
            case 1:
                text = "待完善";
                break;
            case 2:
                text = "待审核";
                break;
            case 3:
                text = "审核通过";
                break;
            case 4:
                text = "审核不通过";
                break;
            case 10:
                text = "暂不认证";
                break;
            case 20:
                text = "审核通过(已读)";
                break;
            default:
                text = "-";
                break;
        }
        return text;
    }

    // 字典查询(提交入口)
    async queryDictData() {
        try {
            const res: any = await this.CustomerShopService.dictListData('submit_auth_source');
            if (res.code == 0) {
                const { list }: any = res.data;
                this.entranceList = list || [];
            }
        } catch (error: any) {
            this.entranceList = [];
            this.message.error(error);
        }
    }

    // 提交入口--文字
    entranceText(source: any) {
        let tempObj: any = this.entranceList.find((item: any) => { return item.content == source });
        return tempObj ? tempObj?.name : '-';
    }
    /**
     * 开启loading
     */
    createBasicMessage(): void {
        this.messageId = this.message.loading('正在请求...', { nzDuration: 0 }).messageId;
    }
    /**
     * 移除loading
     */
    removeBasicMessage() {
        this.message.remove(this.messageId);
        this.messageId = null;
    }
    /**
     * 全局展示操作反馈信息
     * @param type 其他提示类型 success:成功 error:失败 warning：警告
     */
    createMessage(type: any, str: any): void {
        this.message.create(type, str);
    }

    // timeChange
    timeChange(val: any, key: string) {
        this.auditParams[key] = !this.commonService.isEmpty(val) ? format(val, 'yyyy-MM-dd') : '';
    }

    examineChange(val: any) {
        this.auditParams.uscc = '';
        this.auditParams.businessRegisterTime = ''; // 执行注册日期
        this.auditParams.juridicalBirthday = ''; // 法人生日
        this.auditParams.juridicalSex = 0; // 性别 0：位置 1：男 2：女
        // this.auditParams.accountType = ''; // 账号属性 0：正常 1：测试
    }

    // 审核重置状态
    resetStatus() {
        this.modal.confirm({
            nzTitle: '提示',
            nzContent: '确认后，认证状态将变更成待审核?',
            nzOkText: '确认',
            nzCancelText: '取消',
            nzOnOk: async () => {
                let params = {
                    id: this.detailsData.id
                }
                this.resetStatusLoading = true;
                const {code, message}: any = await this.CustomerShopService.resetStatusData(params);
                this.resetStatusLoading = false;

                if (code === 0) {
                    this.message.success('操作成功');
                    this.details();
                } else {
                    this.message.error(message);
                }
            }
        });
    }

    // 账户属性(暂作废20221223)
    preserveAccount() {
        if (this.commonService.isEmpty(this.accountAttribute)) {
            this.message.warning('请先选择账户属性');
            return
        }

        const params = {
            id: this.detailsData.id,
            userId: this.detailsData.userId,
            accountType: this.accountAttribute
        }
        this.subAccountLoaidng = true;
        this.CustomerShopService.audit(params).subscribe((res: any) => {
            this.subAccountLoaidng = false;

            if (res.code === 0) {
                this.message.success('操作成功');
            }
        }, (error: any) => {
            this.subAccountLoaidng = false;
            this.message.error(error);
        })
    }

    // 商家地图属性修改
    showEditMapModal() {
        this.validateMapForm.patchValue({
            mapName: this.detailsData?.mapName || this.detailsData.storeName,
            accountType: this.detailsData.accountType
        })
        this.isMapVisible = true;
    }

    async submitMapForm() {
        if (this.validateMapForm.valid) {
            const params = {
                id: this.detailsData.id,
                ...this.validateMapForm.value
            }
            this.submitMapLoading = true;
            const {code, data}: any = await this.CustomerShopService.updateMapAttributeData(params);
            this.submitMapLoading = false;

            if (code === 0) {
                this.isMapVisible = false;
                this.message.success('操作成功');
                this.details();
            }
        } else {
            Object.values(this.validateMapForm.controls).forEach(control => {
                if (control.invalid) {
                    control.markAsDirty();
                    control.updateValueAndValidity({ onlySelf: true });
                }
            });
        }
    }
}
